<?php
/**
 * Created by PhpStorm.
 * User: gsheng
 * Date: 2019/5/31
 * Time: 8:12 PM
 */

namespace app\index\controller;

use think\Exception;

class User extends Base
{
    /**
     * @return \think\response\Json
     *
     * 登录
     */
    public function login()
    {
        $data = input('param.');
        try {
            $checkName = db('user')
                ->where('phone', '=', $data['phone'])
                ->find();
            $checkPass = db('user')
                ->field('password')
                ->where('phone', '=', $data['phone'])
                ->find();
            if (!$checkName) {
                return getJson('40004', '用户不存在', []);
            } else {
                if (md5($data['password']) != $checkPass['password']) {
                    return getJson('30001', '密码错误', []);
                } else {
                    $res = getJwt($checkName['id']);
                    $info = [
                        'token' => $res,
                        'userInfo' => $checkName
                    ];
                    return getJson('20001', '成功', $info);
                }
            }
        } catch (Exception $e) {
            return json($e->getMessage());
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     *  注册
     */
    public function logup()
    {
        $data = input('param.');
        $is_logup = db('user')->where('username', $data['username'])->find();
        $is_phone = db('user')->where('phone', $data['phone'])->find();
        if (empty($is_logup)) {
            if ($is_phone) {
                return getJson('10002', '手机已经有人用了', []);
            }
            $userData = [
                'username' => $data['username'],
                'password' => md5($data['password']),
                'phone' => $data['phone']
            ];
            $ins = model('user')->data($userData)->save();
            return getJson('20000', '注册成功', $ins);
        } else {
            return getJson('10001', '用户名已经有人用啦～', []);
        }
    }

    /**
     * 修改用户信息
     */
    public function editUserInfo()
    {
        $data = input('param.');
        $user = db('user')->where('id', $data['id'])->update($data);
        return $user;
    }
    public function changePassword()
    {
        $data = input('param.');
        $userPass = db('user')->where('id', $data['id'])->find()['password'];
        if (md5($data['oldPass']) !== $userPass) {
            return getJson('40005', '旧密码有误', []);
        } else {
            $pass =[
                "password" => md5($data['newPass'])
            ];
            $info = db('user')->where('id',$data['id'])->update($pass);
            return json($info);
            return getJson('20003', '修改密码成功', $info);
        }
    }
}